<?php
namespace app\admin\controller;
use think\Db;
use think\facade\{
    Cache,Request
};
class Base extends \think\Controller
{
    public $sys = [];
    public $userinfo = [];
    public function __construct()
    {
        session('js',[]);
        parent::__construct();
        $this->_sys();
        $this->_user();
        $this->_role();
    }

    //系统配置,写入缓存
    private function _sys(){
        $config = Cache::get('sys_config');
        if (empty($config)) {
            $config = model('Deploy')->lists();
            Cache::tag('system_config')->set('sys_config', $config);
        }
        //t($config);
        $this->assign('sys',$config);
    }

    //验证用户登录
    public function _user(){
        $token = session('token');
        $rs = model('AdminUser')::where('token',$token)->find();
        if($token && $rs){
            $this->userinfo = $rs->getData();
            $this->assign('userinfo',$this->userinfo);
        }
        if(com_controller()!='publics' && !$this->userinfo){
                r(url('publics/login'));
        }
    }

    //用户权限,菜单. 写入session: arr_id  菜单加上id的数组
    public function _role(){
        //检查权限
        if(com_controller()!='publics'){
            $url = "/".com_controller()."/".com_action();
            #待解决,首页权限
            if(!in_array(com_controller(), ['api','com']) && session("?right") && !in_array($url, session("right"))){
                if(Request::isAjax()){
                    $this->result([], 200, '没有权限');
                }else{
                    r(url("publics/logout"));
                }
            }
        }
        //菜单session
        //if(session("?arr_id")) return true;
        $menu = c('adminmenu.');
        $arr_id = admin_menu_arr($menu,0);
        if($this->userinfo){
            if($this->userinfo['type']!=1){#非超级管理员
                $group_ids = Db::name("admin_group_user")->where("admin_user_id",$this->userinfo['id'])->column("admin_group_id");
                $rs = Db::name('admin_group')->where("id","in",$group_ids)->column("content");
                $temp = []; #权限
                foreach($rs as $v){
                    $temp = array_merge($temp,explode(",",$v));
                }
                $temp = array_unique(array_filter($temp));
                $temp[] = "/index/index";
                $temp[] = "/adminuser/index";
                session("right", $temp);
                #去掉没有的权限
                foreach($arr_id as $k => $v){
                    if(!in_array($v['url'], $temp)){
                        unset($arr_id[$k]);
                    }
                }
            }
            #将权限写入session
            session("arr_id", $arr_id);
        }
    }
}
